﻿using DongFangGuoKai.TaskPlatform.Commn;
using DongFangGuoKai.TaskPlatform.Commn.Attributes;
using DongFangGuoKai.TaskPlatform.Config;
using DongFangGuoKai.TaskPlatform.Config.Entity;
using DongFangGuoKai.TaskPlatform.WebApi.Extensions;
using Microsoft.AspNetCore.Mvc;
using Quartz;
using System.Reflection;

namespace DongFangGuoKai.TaskPlatform.WebApi.Controllers
{
    /// <summary>
    /// Job
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.V1))]
    public class JobController : ControllerBase
    {

        private readonly SchedulerCenter _SchedulerCenter;

        public JobController(SchedulerCenter schedulerCenter)
        {
            _SchedulerCenter = schedulerCenter;
        }


        [HttpPost]
        [Route("Post")]
       public void  Post()
        {
            Console.WriteLine("POST");
            Console.WriteLine("POST");
        }

        /// <summary>
        /// 获取所有任务
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetAllJob")]
        public async Task<IActionResult> GetAllJob()
        {
            List<JobInfoEntity> data = await _SchedulerCenter.GetAllJobAsync();

            ApiDataResult<List<JobInfoEntity>> result = new ApiDataResult<List<JobInfoEntity>>()
            {
                Data = data,
                Success = true,
                Message = "获取任务列表"
            };


            return new JsonResult(result);
        }


        /// <summary>
        ///上传Job的dll文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpLoadDllFile")]
        public IActionResult UpLoadDllFile([FromForm] IFormFile file)
        {
            string suffix = string.Empty;

            #region  获取文件后缀
            string filename = file.FileName.Trim();
            int index = filename.LastIndexOf(".");
            if (index > 0 && index < filename.Length - 1)
            {
                suffix = filename.Substring(index + 1);
            }
            #endregion

            if (suffix != "dll")
            {
                return new JsonResult("格式错了");

            }
            string saveFilePath = Directory.GetCurrentDirectory();
            if (!Directory.Exists(saveFilePath))
            {
                Directory.CreateDirectory(saveFilePath);
            }

            try
            {
                string allSaveFilePath = $"{saveFilePath}\\Extenddll\\{filename}";
                using (var stream = System.IO.File.Create(allSaveFilePath))
                {
                    file.CopyTo(stream);
                }

                Assembly assembly = Assembly.LoadFrom(saveFilePath);
                Type? type = assembly.GetTypes().FirstOrDefault(t => typeof(IJob).IsAssignableFrom(t));

                ApiDataResult<object> result;

                if (type == null)
                {
                    result = new ApiDataResult<object>()
                    {
                        Success = false,
                        Message = "job必须实现IJob接口"
                    };
                }
                else
                {
                    result = new ApiDataResult<object>()
                    {
                        Success = true,
                        Message = "文件上传成功",
                        Data = new
                        {
                            dllName = filename,
                            typeName = type.FullName
                        }
                    };
                }

                return new JsonResult(result);

            }
            catch (Exception ex)
            {

                throw;
            }
        }

        /// <summary>
        ///获取所有分组名称
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetAllGroup")]
        public async Task<IActionResult> GetAllGroup()
        {
            List<SelectListItem> groupListItem = new List<SelectListItem>();
            var groupNames = await _SchedulerCenter.GetJobGroupNames();
            foreach (var groupName in groupNames)
            {
                groupListItem.Add(new SelectListItem
                {
                    Text = groupName,
                    Value = groupName
                });
            }

            return await Task.FromResult(new JsonResult(new ApiDataResult<List<SelectListItem>>()
            {
                Message = "job分组列表",
                Success = true,
                Data = groupListItem,
                Count = groupListItem.Count
            }));

        }

        /// <summary>
        /// 添加一个任务
        /// （Custom Job Dll）
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("AddJob")]
        public async Task<IActionResult> AddJob(ScheduleEntity entity)
        {
            BaseResult result = await _SchedulerCenter.AddScheduleJobAsync(entity);
            return new JsonResult(result);
        }

        /// <summary>
        /// 添加一个任务
        /// （DongFangGuoKai.Quartz.CustomJob）
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("AddToJob")]
        public async Task<IActionResult> AddToJob(ScheduleEntity entity)
        {
            BaseResult result = await _SchedulerCenter.AddScheduleToJobAsync(entity);
            return new JsonResult(result);
        }

        /// <summary>
        /// 根据自定义Job下拉
        /// </summary>
        /// <param name="assmblayName"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetInstanceByJob")]
        public IActionResult GetJobInstanceByJob(string? name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return new JsonResult(new BaseResult { Code = "400", Success = false, Message = "Job名称不能为空" });
            }

            //任务dll名称
            string assmblayName = "DongFangGuoKai.TaskPlatform.Job.dll";
            //基目录
            string path = AppDomain.CurrentDomain.BaseDirectory;
            path = Path.Combine(path, assmblayName);
            Assembly assembly;
            try
            {
                assembly = Assembly.LoadFile(path);
            }
            catch
            {

                return new JsonResult(new BaseResult
                {
                    Success = false,
                    Message = "读取程序集失败，通知管理员处理异常"
                });
            }

            object jobInstance = null;
            Type? type = assembly.GetType(name);
            if (type == null)
            {
                return new JsonResult(new BaseResult { Code = "400", Success = false, Message = $"未找到【{name}】相关信息" });
            }

            if (type.IsDefined(typeof(JobAttribute), true))
            {

                JobAttribute? attribute = type.GetCustomAttribute<JobAttribute>();
                jobInstance = new
                {
                    Key = attribute.JobKey,
                    Group = attribute.JobGroup,
                    Description = attribute.JobDescription

                };
            }

            ApiDataResult<dynamic> result = new ApiDataResult<dynamic>()
            {
                Data = jobInstance,
                Success = true,
                Message = "获取Job"
            };

            return new JsonResult(result);

        }

        /// <summary>
        /// 获取所有自定义Job
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetAllJobInstance")]
        public IActionResult GetCustomJobInstance()
        {

            //任务dll名称
            string assmblayName = "DongFangGuoKai.TaskPlatform.Job.dll";
            //基目录
            string path = AppDomain.CurrentDomain.BaseDirectory;
            path = Path.Combine(path, assmblayName);
            Assembly assembly;
            try
            {
                assembly = Assembly.LoadFile(path);
            }
            catch
            {

                return new JsonResult(new BaseResult
                {
                    Success = false,
                    Message = "读取程序集失败"
                });
            }

            List<Type> types = assembly.GetTypes().Where(t => typeof(IJob).IsAssignableFrom(t)).ToList();
            List<SelectListItem> jobInstanceListItem = null;
            if (types.Count > 0)
            {
                jobInstanceListItem = new List<SelectListItem>();

                foreach (Type type in types)
                {
                    SelectListItem instance = new SelectListItem();
                    instance.Value = type.FullName;
                    if (type.IsDefined(typeof(JobAttribute), false))
                    {

                        JobAttribute? attribute = type.GetCustomAttribute<JobAttribute>();
                        instance.Text = attribute.JobKey;
                    }
                    else
                    {
                        instance.Text = type.FullName;
                    }

                    jobInstanceListItem.Add(instance);
                }

            }

            return new JsonResult(new ApiDataResult<List<SelectListItem>>()
            {
                Data = jobInstanceListItem,
                Code = "200",
                Message = "自定义Job实例",
                Success = true

            });

        }

        /// <summary>
        ///手动开启任务调度器
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("StartScheduler")]
        public async Task<IActionResult> StartScheduler()
        {
            try
            {
                await _SchedulerCenter.StartSchedule();
                BaseResult result = new BaseResult()
                {
                    Success = true,
                    Message = "开启成功"
                };

                return new JsonResult(result);
            }
            catch (Exception ex)
            {
                return new JsonResult(new BaseResult
                {
                    Success = false,
                    Message = "任务实例异常，开启失败",
                });

            }

        }

        /// <summary>
        /// 继续执行任务
        /// </summary>
        /// <param name="name"></param>
        /// <param name="group"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("ResumeJob/{name}/{group}")]
        public async Task<IActionResult> ResumeJob(string name, string group)
        {
            BaseResult baseResult = await _SchedulerCenter.ResumeJobAsync(group, name);
            return new JsonResult(baseResult);
        }

        /// <summary>
        /// 暂停任务执行
        /// </summary>
        /// <param name="name"></param>
        /// <param name="group"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("StopJob/{name}/{group}")]
        public async Task<IActionResult> StopJob(string name, string group)
        {
            BaseResult baseResult = await _SchedulerCenter.StopOrDeleleteScheduleJobAsync(group, name);
            return new JsonResult(baseResult);
        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="group"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("RemoveJob/{name}/{group}")]
        public async Task<IActionResult> RemoveJob(string name, string group)
        {
            BaseResult baseResult = await _SchedulerCenter.StopOrDeleleteScheduleJobAsync(group, name, true);
            return new JsonResult(baseResult);
        }

        /// <summary>
        /// 立即执行
        /// </summary>
        /// <param name="group"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("TriggerJob/{name}/{group}")]
        public async Task<IActionResult> TriggerJob(string name, string group)
        {
            if (await _SchedulerCenter.TriggerJobAsync(new JobKey(name, group)))
            {
                return new JsonResult(new BaseResult()
                {
                    Success = true,
                    Message = "执行成功"
                });
            }
            else
            {
                return new JsonResult(new BaseResult()
                {
                    Success = false,
                    Message = "执行失败"
                });
            }
        }


    }
}
